// 游戏板大小
const BOARD_SIZE = 9;
// 初始化游戏板
const gameBoard = document.getElementById('game-board');
const message = document.getElementById('message');
let board = Array.from({ length: BOARD_SIZE }, () => Array(BOARD_SIZE).fill(0));
let catPosition = [4, 4];
let gameOver = false;

// 创建游戏板
function createBoard() {
    for (let i = 0; i < BOARD_SIZE; i++) {
        for (let j = 0; j < BOARD_SIZE; j++) {
            const cell = document.createElement('div');
            cell.classList.add('cell');
            cell.dataset.row = i;
            cell.dataset.col = j;
            cell.addEventListener('click', handleCellClick);
            gameBoard.appendChild(cell);
        }
    }
    updateBoard();
}

// 更新游戏板显示
function updateBoard() {
    const cells = gameBoard.querySelectorAll('.cell');
    cells.forEach(cell => {
        const row = parseInt(cell.dataset.row);
        const col = parseInt(cell.dataset.col);
        cell.textContent = '';
        cell.classList.remove('cat', 'block');
        if (row === catPosition[0] && col === catPosition[1]) {
            cell.textContent = '🐱';
            cell.classList.add('cat');
        } else if (board[row][col] === 1) {
            cell.classList.add('block');
        }
    });
}

// 处理单元格点击事件
function handleCellClick() {
    if (gameOver) return;
    const row = parseInt(this.dataset.row);
    const col = parseInt(this.dataset.col);
    if (board[row][col] === 0 && !(row === catPosition[0] && col === catPosition[1])) {
        board[row][col] = 1;
        updateBoard();
        moveCat();
    }
}

// 猫移动逻辑
function moveCat() {
    const directions = [
        [-1, 0], [1, 0], [0, -1], [0, 1]
    ];
    let bestMove = null;
    let minDistance = Infinity;

    for (const [dx, dy] of directions) {
        const newRow = catPosition[0] + dx;
        const newCol = catPosition[1] + dy;
        if (newRow >= 0 && newRow < BOARD_SIZE && newCol >= 0 && newCol < BOARD_SIZE && board[newRow][newCol] === 0) {
            const distanceToEdge = Math.min(newRow, BOARD_SIZE - 1 - newRow, newCol, BOARD_SIZE - 1 - newCol);
            if (distanceToEdge < minDistance) {
                minDistance = distanceToEdge;
                bestMove = [newRow, newCol];
            }
        }
    }

    if (bestMove) {
        catPosition = bestMove;
        updateBoard();
        if (isCatTrapped()) {
            gameOver = true;
            message.textContent = '你成功围住了神经猫！';
            saveGameResult('win');
        }
    } else {
        gameOver = true;
        message.textContent = '神经猫逃脱了！';
        saveGameResult('lose');
    }
}

// 检查猫是否被困住
function isCatTrapped() {
    const directions = [
        [-1, 0], [1, 0], [0, -1], [0, 1]
    ];
    for (const [dx, dy] of directions) {
        const newRow = catPosition[0] + dx;
        const newCol = catPosition[1] + dy;
        if (newRow >= 0 && newRow < BOARD_SIZE && newCol >= 0 && newCol < BOARD_SIZE && board[newRow][newCol] === 0) {
            return false;
        }
    }
    return true;
}

// 保存游戏结果到服务器
function saveGameResult(result) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'save_result.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText);
        }
    };
    xhr.send(`result=${result}`);
}

// 初始化游戏
createBoard();